﻿using AwesomeChromeFormUI.Attributes;
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;

namespace AwesomeChromeFormUI.Reflections
{
    public static class ClassUtil
    {

        /// <summary>
        /// 扫描带注解的类
        /// 例如扫描 Bean
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static void FindAllAttributeClasses<T>() where T : Attribute
        {
            Type[] types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(a => a.GetTypes())
                .Where(t => t.IsClass && t.GetCustomAttribute<T>() != null)
                .ToArray();

            foreach (Type type in types)
            {
                Debug.WriteLine("找到带注解的class: " + type.Name);
                PrintAtrributes(type);
            }
        }

        /// <summary>
        /// 打印注解
        /// </summary>
        public static void PrintAtrributes(Type type)
        {
            Attribute[] attrs = Attribute.GetCustomAttributes(type);

            foreach (Attribute attr in attrs)
            {
                if (attr is BeanAttribute beanAttribute)
                {
                    Debug.WriteLine("Name => " + beanAttribute.Name);
                }
            }
        }

        private static void FindClassByName()
        {
            string className = "MyClass"; // 要查找的类名

            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

            foreach (Assembly assembly in assemblies)
            {
                Type type = assembly.GetTypes().FirstOrDefault(t => t.Name == className);
                if (type != null)
                {
                    Console.WriteLine("找到类: " + type.FullName);
                    // 找到了类，可以进行后续操作
                    break; // 如果只需要找到一个匹配的类，可以结束循环
                }
            }

        }
    }
}
